package se.ytterman.jpcap.pcap;

import java.lang.*;
import java.io.*;
import java.util.*;

public class PcapPacket {

    public PcapPacket() {
	// Assign new buffer storage
	this.buffer = new byte[0];
    }

    public PcapPacket(byte[] buffer) {
	// Assign buffer
	this.buffer = buffer;
    }

    public byte[] getPayload() {
	return this.buffer;
    }

    public void printBitdump(PrintStream out) {
	// Print table head
	out.printf("------------------------------------------\n");
	out.printf("%04d-|......00|......01|......02|......03|\n",
			  buffer.length);
	out.printf("-----|--------|--------|--------|--------|\n");

	// Row counter
	int row = 0;

	while((row*0x04) < buffer.length) {
	    // Print row head
	    out.printf("%04X-|", (row*0x04));
	    
	    // Column counter
	    for(int col = 0; col < 0x04; col++) {
		// Calculate buffer index
		int index = (row*0x04 + col);

		// Check if we are withing the array...
		if(index < buffer.length) {
		    // Convert byte to binary "string" if there is buffer left
		    for(int shift = 0; shift <= 7; shift++) {
			if(((buffer[index] << shift) & 0x80) == 0x80)
			    out.printf("1");
			else
			    out.printf("0");
		    }
		    out.printf("|");
		}
		else {
		    // Print bogus if byte array is finished
		    out.printf("XXXXXXXX|");
		}
	    }

	    // Print row end
	    out.printf("\n");

	    // Increment row counter
	    row++;
	}
	
	// Print table end
	out.printf("------------------------------------------\n");
    }

    public void printHexdump(PrintStream out) {
	// Print table head
	out.printf("-----------------------------------------------------\n");
	out.printf("%04d-|00|01|02|03|04|05|06|07|08|09|0A|0B|0C|0D|0E|0F|\n",
			  buffer.length);
	out.printf("-----|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|\n");

	// Row counter
	int row = 0;

	while((row*0x10) < buffer.length) {
	    // Print row head
	    out.printf("%04X-|", (row*0x10));
	    
	    // Column counter
	    for(int col = 0; col < 0x10; col++) {
		// Calculate buffer index
		int index = (row*0x10 + col);

		// Check if we are withing the array...
		if(index < buffer.length) {
		    out.printf("%02X|", buffer[index]);
		}
		else {
		    out.printf("XX|");
		}
	    }

	    // Print row end
	    out.printf("\n");

	    // Increment row counter
	    row++;
	}
	
	// Print table end
	out.printf("-----------------------------------------------------\n");
    }

    private long timestamp;
    private byte[] buffer;
}
